﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Data.Entity;
using Wedo.Recognition.Web.Models;
 
using Wedo.Mvc.Utility;
using System.Security.Principal;
using Wedo.Service.Common;
using Wedo.Recognition.Domain;
using EFCachingProvider.Caching;
using EFCachingProvider; 
using Microsoft.Practices.Unity;
using Wedo.Recognition.Domain;
using Wedo.Recognition.Service;
using System.Data.Common;
using Wedo.Recognition.Web;

namespace Recognition
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : System.Web.HttpApplication
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
            filters.Add(new Wedo.Mvc.Utility.Filter.AppHandleErrorFilter());
            filters.Add(new UrlFilter());

            //filters.Add(new SetCultureAttribute());
         }

        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            routes.IgnoreRoute("{resource}.js/{*pathInfo}");
            routes.IgnoreRoute("{resource}.css/{*pathInfo}");
            routes.IgnoreRoute("{resource}.png/{*pathInfo}");
            routes.IgnoreRoute("{resource}.jpg/{*pathInfo}");
            routes.IgnoreRoute("{resource}.gif/{*pathInfo}");

            routes.MapRoute(
                "Default", // Route name
                "{controller}/{action}/{id}", // URL with parameters
                new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
            );
            
        }

        #region 查询用户
        public override void Init()
        {
            this.PostAuthenticateRequest += this.PostAuthenticateRequestHandler;
            base.Init();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void PostAuthenticateRequestHandler(object sender, EventArgs e)
        {
            if (IgnoreAuthenticate(Context.Request.RawUrl)==false
                &&(Context.User.Identity is CurrentUser) == false)
            {
                SetContextUser();
            }
        }

        /// <summary>
        /// 忽略验证权限的文件
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        private bool IgnoreAuthenticate(string url)
        {
            string[] Suffixs = { ".css", ".js", ".png", ".jpg", ".gif",".ico" };
            url = url.ToLower();
            if (Suffixs.Any(m => url.EndsWith(m)))
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        private CurrentUser GetDBUser()
        {
            UserService service = new UserService(Container_Config.GetIUnitWork());
            return service.GetPageUser(User.Identity.Name);
        }

        private CurrentUser GetPageUser()
        {
            //获取Coockie中用户信息
            CurrentUser user = CookieSecurity.GetUser(Request);

            if (CookieSecurity.IsLogoned(Request, user) == false)
            {
                user = GetDBUser();
                if (user != null && user.IsAuthenticated)
                {
                    CookieSecurity.CreateUserCookie(Response, Request, user);
                }
            }
            return user;
        }

        private void SetContextUser()
        {
            var user = GetPageUser();
            //GetDBUser(); 

            if (user == null)
            {
                user = new CurrentUser(User.Identity.Name);
            }

            Context.User = new GenericPrincipal(user, user.Roles);
        }

        #endregion

        protected void Application_Start()
        {
#if DEBUG
            Database.SetInitializer(new CreateTestData());
            DbConnection connection= EFProviderWrapperToolkit.ConnectionWrapperUtils.CreateCommonConnection("name=EFDbContext"); 
            using (EFDbContext context = new Wedo.Recognition.Domain.EFDbContext(
               connection, true))
            {
                context.Database.Initialize(false);
            }
#endif

            
            AreaRegistration.RegisterAllAreas();
            IUnityContainer container = Container_Config.GetContainer_Config();


            EFCachingProviderConfiguration.DefaultCache = new AspNetCache();
            EFCachingProviderConfiguration.DefaultCachingPolicy =new CustomCachingPolicy();
            CompetenceConfig.ActionCompetence = new WebActionCompetence();

            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);
            ControllerBuilder.Current.SetControllerFactory(new UnityControllerFactory(container));

        } 

    }
}